<template>
  <div class="vue">
    <el-divider content-position="center" class="title"
      >用户账户基本信息</el-divider
    >
    <div class="form-container">
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        size="default"
        label-width="100px"
        class="custom-form"
      >
        <el-descriptions :column="2" border class="custom-descriptions">
          <el-descriptions-item label="账户号">{{
            formData.accountid
          }}</el-descriptions-item>
          <el-descriptions-item label="银行卡号">{{
            formData.cardNumber
          }}</el-descriptions-item>
          <el-descriptions-item label="登录名">{{
            formData.username
          }}</el-descriptions-item>
          <el-descriptions-item label="手机号">{{
            formData.phoneNumber
          }}</el-descriptions-item>
          <el-descriptions-item label="身份证号">{{
            formData.identifiNumber
          }}</el-descriptions-item>


          <el-descriptions-item label="用户邮箱">
      {{ formData.email || '无' }}
    </el-descriptions-item>


          <el-descriptions-item label="账户状态">
            <span v-if="formData.status === 0">未激活</span>
            <span v-else-if="formData.status === 1">正常</span>
            <span v-else>冻结</span>
          </el-descriptions-item>
          <el-descriptions-item label="账户余额"
            >{{ formData.balance }}￥</el-descriptions-item
          >
        </el-descriptions>
      </el-form>
    </div>

    <el-divider content-position="center" class="title"
      >用户可执行操作</el-divider
    >
    <div class="content-container">
      <el-row :gutter="20" class="options">
        <el-col :span="8">
          <el-form
            :model="queryParams"
            ref="queryRef"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
          >
            <el-form-item label="账户号" prop="otherId" class="search">
              <el-input
                v-model="queryParams.otherId"
                placeholder="请输入账户号"
                clearable
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                class="handle"
                icon="Search"
                @click="handleQuery"
                >搜索</el-button
              >
            </el-form-item>
          </el-form>
        </el-col>
        <el-col :span="16">
          <el-form-item class="form-item-btn">
            <el-button type="primary" @click="getAccountWithMoey()"
              >取款</el-button
            >
            <el-button type="primary" @click="getAccountDeposit()"
              >存款</el-button
            >
            <el-button type="primary" @click="getAccountTransFer()"
              >转账</el-button
            >
          </el-form-item>
        </el-col>
      </el-row>
    </div>

    <!-- 添加或修改课程管理对话框 -->
    <el-dialog :title="title" v-model="openDe" width="500px" append-to-body @close="handleClose">
      <el-form ref="courseRef" :model="deList" label-width="80px">
        <el-form-item
          label="账户号"
          prop="accountid"
          class="single-line"
          :error="v$.accountid.$error ? v$.accountid.$errors[0].$message : ''"
        >
          <el-input v-model="deList.accountid" placeholder="请输入账户号" />
        </el-form-item>

        <el-form-item
          class="single-line"
          label="对方账户号"
          prop="otherId"
          :error="v$.otherId.$error ? v$.otherId.$errors[0].$message : ''"
          v-if="deList.code == '3'"
        >
          <el-input v-model="deList.otherId" placeholder="请输入对方账户号" />
        </el-form-item>

        <el-form-item
          class="single-line"
          label="银行卡号"
          prop="cardNumber"
          :error="v$.cardNumber.$error ? v$.cardNumber.$errors[0].$message : ''"
        >
          <el-input v-model="deList.cardNumber" placeholder="请输入银行卡号" />
        </el-form-item>
        <el-form-item
          label="用户名"
          prop="username"
          class="single-line"
          :error="v$.username.$error ? v$.username.$errors[0].$message : ''"
        >
          <el-input v-model="deList.username" placeholder="请输入用户名称" />
        </el-form-item>
        <el-form-item
          label="密码"
          prop="password"
          class="single-line"
          :error="v$.password.$error ? v$.password.$errors[0].$message : ''"
        >
          <el-input
            type="password"
            v-model="deList.password"
            placeholder="请输入密码"
            class="single-line"
          />
        </el-form-item>
        <el-form-item
          label="身份证号"
          prop="identifiNumber"
          class="single-line"
          :error="
            v$.identifiNumber.$error
              ? v$.identifiNumber.$errors[0].$message
              : ''
          "
        >
          <el-input
            v-model="deList.identifiNumber"
            placeholder="请输入身份证号"
          />
        </el-form-item>
        <el-form-item
          :label="labelText"
          prop="balance"
          class="single-line"
          :error="v$.balance.$error ? v$.balance.$errors[0].$message : ''"
        >
          <el-input
            v-model.number="deList.balance"
            :placeholder="dynamicPlaceholder"
            @input="handleInput"
            type="text"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="getDepositConfirm">确定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import {
  getAccountInfo,
  getUserAccount,
  getAccountFromAPI,
  getUserStatus,
} from "@/api/account/account.js";

import { ElMessage, ElMessageBox } from "element-plus";

import useUserStore from "@/store/modules/user";
const userStore = useUserStore();

// 更新code值
function updateCode() {
  console.log("userStore.code---" + userStore.code);
  // 定义可用字符集
  const chars =
    "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
  let result = "";
  const length = 5; // 需要生成的字符长度

  // 循环添加随机字符到结果字符串
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    result += chars[randomIndex];
  }
  userStore.setCode(result);
  console.log("userStore.code---" + userStore.code);
}

const formRef = ref();
const data = reactive({
  formData: {
    accountid: undefined,
    cardNumber: undefined,
    username: undefined,
    password: undefined,
    phoneNumber: undefined,
    identifiNumber: undefined,
    email: undefined,
    status: undefined,
    balance: undefined,
  },
  rules: {
    accountId: [
      {
        required: true,
        message: "请输入账户号 ",
        trigger: "blur",
      },
    ],
    cardNumber: [
      {
        required: true,
        message: "请输入银行卡号",
        trigger: "blur",
      },
    ],
    username: [
      {
        required: true,
        message: "请输入登录名",
        trigger: "blur",
      },
    ],
    password: [
      {
        required: true,
        message: "请输入密码",
        trigger: "blur",
      },
    ],
    phoneNumber: [
      {
        required: true,
        message: "请输入手机号",
        trigger: "blur",
      },
    ],
    identifiNumber: [
      {
        required: true,
        message: "请输入身份证号",
        trigger: "blur",
      },
    ],
    email: [
      {
        required: true,
        message: "请输入用户邮箱",
        trigger: "blur",
      },
    ],
    status: [
      {
        required: true,
        message: "请输入账户状态",
        trigger: "blur",
      },
    ],
  },
});
const title = ref("");
const { formData, rules } = toRefs(data);

const showSearch = ref(true);

const queryParams = ref({
  otherId: "",
});

// 创建code
const code = ref("initialCode");
const labelText = ref("输入金额");
const dynamicPlaceholder = ref("请输入存入金额");
/** 进行输入验证 */
import { ref, computed } from "vue";
import useVuelidate from "@vuelidate/core";
import { required, helpers } from "@vuelidate/validators";
/* import { fa } from "element-plus/es/locale"; */

// 自定义验证规则：确保身份证号为18位或15位数字（最后一位可以是X或x）
const isValidIdNumber = (value) => {
  return /^(?:\d{15}|\d{17}[\dXx])$/.test(value);
};
// 响应式数据对象
const deList = ref({
  code: null,
  accountid: null,
  otherId: null,
  cardNumber: null,
  username: null,
  password: null,
  identifiNumber: null,
  balance: null,
  phoneNumber: null, // 确保所有字段都在这里定义
});

// 定义验证规则
const deRules = computed(() => ({
  accountid: { required },
  otherId: { required },
  cardNumber: { required },
  username: { required },
  password: { required },
  phoneNumber: { required },
  identifiNumber: {
    required,
    isValidIdNumber: helpers.withMessage(
      "请输入有效的身份证号",
      isValidIdNumber
    ),
  },
  balance: {
    required,
    minValue: helpers.withMessage("余额必须大于0", (value) => value > 0),
    maxValue: helpers.withMessage(
      "余额必须小于等于10000",
      (value) => value <= 10000
    ),
  },
}));
const formattedBalance = ref('');
function handleInput(event) {
  const value = event.target.value.replace(/,/g, '');
  formattedBalance.value = value;
  deList.value.balance = parseFloat(value);
}
// 初始化 Vuelidate
const v$ = useVuelidate(deRules, deList);
// 确保在组件挂载后初始化验证器
onMounted(() => {
  v$.value.$touch();
});

// 提交表单的方法
// 提交表单的方法
const getDepositConfirm = async () => {
  const result = await v$.value.$validate(); // 触发验证
  if (!result) {
    // 如果有验证错误，显示提示信息
    console.log("请修正表单中的错误");
  }
  ElMessageBox.confirm("确认执行此操作吗?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      getUserAccount(deList.value).then((res) => {
        // 成功后的提示
        ElMessage({
          type: "success",
          message: "操作成功!",
        });
        openDe.value = false;
        reset()
        console.log("deList.value.code:" + deList.value.code);
        updateCode();
        getAccount();
      });
    })
    .catch(() => {
      // 取消操作的提示
      ElMessage({
        type: "info",
        message: "已取消操作",
      });
    });
};

function handleClose() {
    reset();
};
// 取消按钮
function cancel() {
  reset();
  openDe.value = false;
}
// 将需要的变量和方法暴露给模板
defineExpose({ deList, v$, getDepositConfirm, cancel });
/**
 * @name: 表单提交
 * @description: 表单提交方法
 * @return {*}
 */
function submitForm() {
  formRef.value.validate((valid) => {
    if (!valid) return;
    // TODO 提交表单
  });
}
/**
 * @name: 表单重置
 * @description: 表单重置方法
 * @return {*}
 */
function resetForm() {
  formRef.value.resetFields();
}
/** 查询指定用户账户信息 */
function getAccount() {
  getAccountInfo().then((response) => {
    formData.value = response.data;
  });
}
/** 进行存款操作 */

const openDe = ref(false);
function getAccountDeposit() {
  getUserStatus(formData.value.accountid).then((res) => {
    if (res.code === 200 && res.msg === "用户状态正常") {
      // 显示成功提示
      ElMessage({
        message: "用户状态正常",
        type: "success",
        duration: 1000, // 设置消息持续时间为3秒
        onClose: () => {
          // 在消息提示框关闭后打开弹窗
          openDe.value = true;
        }
      });
      deList.value.code = "1";
      title.value = "存款管理";
      code.value = "1";
      console.log("Code updated to:", code.value);
      labelText.value = "存款金额";
      dynamicPlaceholder.value = "请输入存款金额";
      console.log("Label text updated to:", labelText.value);

    } else {
      // 显示错误提示
      ElMessage({
        message: "用户状态异常",
        type: "error",
      });
    }
  });
}
function getAccountWithMoey() {
  getUserStatus(formData.value.accountid).then((res) => {
    if (res.code === 200 && res.msg === "用户状态正常") {
      // 显示成功提示
      ElMessage({
        message: "用户状态正常",
        type: "success",
        duration: 1000, // 设置消息持续时间为3秒
        onClose: () => {
          // 在消息提示框关闭后打开弹窗
          openDe.value = true;
        }
      });
      deList.value.code = "2";
      title.value = "取款管理";
      code.value = "2";
      console.log("Code updated to:", code.value);
      labelText.value = "取款金额";
      dynamicPlaceholder.value = "请输入取款金额";
      console.log("Label text updated to:", labelText.value);
    } else {
      // 显示错误提示
      ElMessage({
        message: "用户状态异常",
        type: "error",
      });
    }
  });
}
function getAccountTransFer() {
  getUserStatus(formData.value.accountid).then((res) => {
    if (res.code === 200 && res.msg === "用户状态正常") {
      // 显示成功提示
      ElMessage({
        message: "用户状态正常",
        type: "success",
        duration: 1000, // 设置消息持续时间为3秒
        onClose: () => {
          // 在消息提示框关闭后打开弹窗
          openDe.value = true;  
        }
      });
      deList.value.code = "3";
      title.value = "转账管理";
      code.value = "3";
      console.log("Code updated to:", code.value);
      labelText.value = "转账金额";
      dynamicPlaceholder.value = "请输入转账金额";
      console.log("Label text updated to:", labelText.value);
    } else {
      // 显示错误提示
      ElMessage({
        message: "用户状态异常",
        type: "error",
      });
    }
  });
}
function reset() {
  deList.value = {
    accountid: null,
    cardNumber: null,
    username: null,
    password: null,
    identifiNumber: null,
    balance: null,
  };
}

getAccount();

/** 搜索按钮操作 */
function handleQuery() {
  console.log("查询条件:", queryParams.value);
  getAccountFromAPI(queryParams.value.otherId)
    .then((res) => {
      // 处理响应数据
      console.log(res.value);
      console.log(res);
      if (res.code === 200 && res.msg === "查询用户存在") {
        // 显示成功提示
        ElMessage({
          message: "查询用户存在",
          type: "success",
        });
      }
    })
    .catch((error) => {
      // 处理错误
    });
}
</script>

<style>
.form-item-btn {
  display: flex;
  justify-content: flex-end;
  margin-left: 80px;
}
.handle {
  margin-left: 110px;
}
.search {
  margin-left: 40px;
}

.form-container {
  margin-top: 30px; /* 表单整体下移 */
  padding: 0 30px; /* 左右留白 */
}

.custom-form {
  max-width: 1000px;
  margin: 0 auto; /* 水平居中 */
}

.custom-descriptions .el-descriptions-item {
  margin-bottom: 50px; /* 调整每一项之间的间距 */
}
.title {
  margin-top: 40px;
}
.content-container {
  margin-top: 50px; /* 整体下移 */
}

/* 确保 .single-line 类下的内容占据整行 */
.single-line {
  display: flex;
  align-items: center;
}

.single-line .el-form-item__content {
  margin-left: 0 !important; /* 移除默认的标签与输入框之间的间距 */
  width: 100%; /* 输入框占据整个容器宽度 */
}

.single-line .el-form-item__label {
  flex: none; /* 固定标签宽度 */
  width: auto; /* 自动适应标签文本宽度 */
  padding-right: 8px; /* 可选：为标签和输入框之间添加一些间距 */
}
</style>
